package com.amoyt.project.controller.web;

import com.amoyt.project.config.minio.MinIOConfig;
import com.amoyt.project.constants.ResponseConstants;
import com.amoyt.project.domain.res.Result;
import com.amoyt.project.utils.MinIOUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName FileController
 * @Author AmoyT
 * @Version 1.0
 * @Description 文件（图片，音视频）上传类
 **/
@RestController
@RequestMapping("/web/file")
@Tag(name = "文件上传接口",description = "文件上传接口")
@Slf4j
public class FileController {

    @Autowired
    private MinIOConfig minIOConfig;

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @Operation(summary = "上传图片",method = "POST")
    @PostMapping("/uploadImg")
    public Result uploadImage(@RequestParam("file") MultipartFile file) throws Exception {

        // 获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            //文件不能为空
            return Result.error(ResponseConstants.FILE_UPLOAD_NULL_ERROR);

        }

        //终极路径
        filename = "image/" + dealWithoutFilename(filename);
        //上传获得图片地址
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                                                filename,
                                                file.getInputStream(),
                                                true);

        //返回图片地址
        log.info("图片上传成功！imageUrl:{}", imageUrl);
        return Result.success(ResponseConstants.UPLOAD_SUCCESS, imageUrl);
    }

    /**
     * 上传其他文件
     * @param file
     * @return
     * @throws Exception
     */
    @Operation(summary = "上传其他文件",method = "POST")
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws Exception {

        // 获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            //文件不能为空
            return Result.error(ResponseConstants.FILE_UPLOAD_NULL_ERROR);
        }

        filename = "file/" + dealWithoutFilename(filename);
        String fileUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),
                true);

        log.info("文件上传成功！fileUrl："+fileUrl);
        return Result.success(ResponseConstants.UPLOAD_SUCCESS, fileUrl);
    }

    /**
     * 上传文件原始名 -保持原始名
     * @param file
     * @param flag 标记：video，file，image
     * @return
     */
    @Operation(summary = "上传文件原始名",method = "POST")
    @PostMapping("/originalFile/{flag}")
    public Result originFile(@RequestParam("file") MultipartFile file, @PathVariable("flag") String flag) throws Exception {
        // 获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            //文件不能为空
            return Result.error(ResponseConstants.FILE_UPLOAD_NULL_ERROR);
        }

        filename = flag + "/" + filename;
        String fileUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),
                true);
        log.info("文件上传成功！fileUrl："+fileUrl);
        return Result.success(ResponseConstants.UPLOAD_SUCCESS, fileUrl);
    }


    /**
     * 处理文件名 携带本身文件名
     * @param filename
     * @return
     */
    private String dealWithFilename(String filename) {
        // 获取文件后缀名
        String suffixName = filename.substring(filename.lastIndexOf("."));
        // 截取文件名
        String fName = filename.substring(0, filename.lastIndexOf("."));

        // 生成不带短横线的UUID
        //String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        String uuid = UUID.randomUUID().toString();
        // 拼接uuid + 文件名 + 后缀
        return fName + "-" + uuid + suffixName;
    }

    /**
     * 处理文件名 不携带文件名
     * @param filename
     * @return
     */
    private String dealWithoutFilename(String filename) {
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return uuid + suffixName;
    }

}
